package com.example.shixun1.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.example.shixun1.Fragment.HeadlinesFragment;
import com.example.shixun1.Fragment.MallFragment;
import com.example.shixun1.Fragment.MeFragment;
import com.example.shixun1.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 登录检查
        SharedPreferences prefs = getSharedPreferences("login_state", MODE_PRIVATE);
        if (!prefs.getBoolean("is_logged_in", false)) {
            redirectToLogin();
            return;
        }

        setContentView(R.layout.activity_main);
        setupNavigation();
    }

    private void setupNavigation() {
        BottomNavigationView navView = findViewById(R.id.bottom_navigation);
        navView.setOnNavigationItemSelectedListener(item -> {
            Fragment fragment = null;
            int id = item.getItemId();

            if (id == R.id.nav_headlines) {
                fragment = new HeadlinesFragment();
            } else if (id == R.id.nav_mall) {
                fragment = new MallFragment();
            } else if (id == R.id.nav_me) {
                fragment = new MeFragment();
            }

            if (fragment != null) {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_container, fragment)
                        .commit();
                return true;
            }
            return false;
        });

        // 默认加载头条Fragment
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, new HeadlinesFragment())
                .commit();
    }

    private void redirectToLogin() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }
}